package com.stonedt.spider.controller.autoIndustry;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.stonedt.spider.controller.overseas.OverseasInfo;
import com.stonedt.spider.util.UtilConfig;

/**
 * 汽车大全
 * @date  2020年2月6日 下午2:43:45
 */
@Controller
@RequestMapping("/carDaquan")
public class CarDaquanController {
	
//	private final String es_url = "http://s1.stonedt.com:6303";
	private final String es_url = UtilConfig.getURL2().substring(0,UtilConfig.getURL2().length()-1);
	
	private final String carlist_api = "/car/carlist";
	private final String getinvitatedetail_api = "/car/getinvitatedetail";
	
    private final String[] car_types = new String[] {
		"跑车", "紧凑型车", "中型车", "中大型车", "中型SUV", "紧凑型SUV", "中大型SUV", 
		"MPV", "大型车", "小型车", "小型SUV", "微型车", "大型SUV", "高端皮卡", "轻客"
	};
    
	/**
	 * 车型列表
	 */
	@RequestMapping(value = "/carTypes", produces = "application/json;charset=utf-8")
	@ResponseBody
	public String carTypes() {
		return JSON.toJSONString(car_types);
	}

	/**
	 * 汽车数据
	 */
	@RequestMapping(value = "/carlist", produces = "application/json;charset=utf-8")
	@ResponseBody
	public String carlist(String pageNum, int searchType, String searchkeyword) {
		
		JSONArray array=new JSONArray();
		JSONArray Array=new JSONArray();
		JSONObject mapJson = new JSONObject();
		mapJson.put("timefield","spider_time");
		mapJson.put("times","");
		mapJson.put("size","20");
		mapJson.put("index","stonedt_car");
		mapJson.put("page", pageNum);
		mapJson.put("type","infor");
		mapJson.put("timee","");
//		JSONObject json1=new JSONObject();
//		json1.put("field", "website_name");
//		json1.put("keyword", "汽车之家");
//        array.add(json1);
        
        if(searchkeyword!=null && searchkeyword!="") {
        	if(searchType==1) {//车名
        		JSONObject json2=new JSONObject();
        		json2.put("field", "model");
        		json2.put("keyword", searchkeyword);
                array.add(json2);
        		mapJson.put("and",array);
        	}else if(searchType==2) {//车牌名
        		JSONObject json2=new JSONObject();
        		json2.put("field", "brand");
        		json2.put("keyword", searchkeyword);
                array.add(json2);
        		mapJson.put("and",array);
        	}else {
        		JSONObject json2=new JSONObject();
        		json2.put("field", "brand");
        		json2.put("keyword", searchkeyword);
        		Array.add(json2);
                JSONObject json3=new JSONObject();
        		json3.put("field", "model");
        		json3.put("keyword", searchkeyword);
                Array.add(json3);
                mapJson.put("or",Array);
        	}
        }
		System.err.println(mapJson.toString());
	
		
		String response = "";
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, String>> list = new ArrayList<>();
		try {
//			System.err.println(carlist_api);
//			response = esArticle(map, carlist_api);
			String url = "http://dx2.stonedt.com:7120/commonsearch/superdatalist";
			response =  OverseasInfo.sendPostRaw(mapJson.toJSONString(),url,"utf-8");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("list", list);
			result.put("totalData", 0);
			result.put("totalPage", 1);
		}
		if (StringUtils.isNotBlank(response)) {
			JSONObject parseObject = JSON.parseObject(response);
			String totalData = parseObject.getString("count");
			String totalPage = parseObject.getString("page_count");
			JSONArray jsonArray = parseObject.getJSONArray("data");
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				JSONObject jsonObject2 = jsonObject.getJSONObject("_source");
				Map<String, String> params = JSONObject.parseObject(jsonObject2.toJSONString(), new TypeReference<Map<String, String>>(){});
				list.add(params);
			}
			if (Integer.parseInt(totalData) > 5000) {
				totalPage = "500";
			}
			if (StringUtils.isBlank(totalPage)) {
				totalPage = "1";
			}else if ("0".equals(totalPage)) {
				totalPage = "1";
			}
			result.put("list", list);
			result.put("totalData", totalData);
			result.put("totalPage", totalPage);
		}else {
			result.put("list", list);
			result.put("totalData", 0);
			result.put("totalPage", 1);
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 汽车详情
	 */
	@RequestMapping(value = "/detail", produces = "application/json;charset=utf-8")
	@ResponseBody
	public String detail(String article_public_id) {
		String url = es_url + getinvitatedetail_api;
		String param = "article_public_id=" + article_public_id;
		System.err.println(url + "?" + param);
		String response = "";
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			response = sendPost(url, param);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Map<String, String> data = new HashMap<>();
		List<String> yearData1 = new ArrayList<>();
		List<String> yearData2 = new ArrayList<>();
		List<String> monthData1 = new ArrayList<>();
		List<String> monthData2 = new ArrayList<>();
		if (StringUtils.isNotBlank(response)) {
			data = JSONObject.parseObject(response, new TypeReference<Map<String, String>>(){});
			JSONObject parseObject = JSON.parseObject(response);
			if (parseObject.containsKey("evaluation_of_years")) {
				Map<String, String> data1 = 
						JSONObject.parseObject(parseObject.getString("evaluation_of_years"),
								new TypeReference<Map<String, String>>(){});
				Iterator<Entry<String, String>> it = data1.entrySet().iterator();
			    while(it.hasNext()) {
			        Entry<String, String> entry = it.next();
			        yearData1.add(entry.getKey());
			        yearData2.add(entry.getValue());
			    }
			}
			if (parseObject.containsKey("evaluation_of_month")) {
				Map<String, String> data1 = 
						JSONObject.parseObject(parseObject.getString("evaluation_of_month"),
								new TypeReference<Map<String, String>>(){});
				Iterator<Entry<String, String>> it = data1.entrySet().iterator();
			    while(it.hasNext()) {
			        Entry<String, String> entry = it.next();
			        monthData1.add(entry.getKey());
			        monthData2.add(entry.getValue());
			    }
			}
		}
		result.put("data", data);
		result.put("yearData1", yearData1);
		result.put("yearData2", yearData2);
		result.put("monthData1", monthData1);
		result.put("monthData2", monthData2);
		return JSON.toJSONString(result);
	}
	
	@RequestMapping(value = "/car-daquan", method = RequestMethod.GET)
	public ModelAndView mainstreamMediaList(ModelAndView mv) {
		mv.setViewName("autoIndustry/car-daquan");
		return mv;
	}
	
	@RequestMapping(value = "/car-daquan-detail", method = RequestMethod.GET)
	public ModelAndView detail(ModelAndView mv) {
		mv.setViewName("autoIndustry/car-daquan-detail");
		return mv;
	}
	
	//查询销量一级类目
	
	@RequestMapping(value = "/car-sales", method = RequestMethod.GET)
	public ModelAndView sales(ModelAndView mv) {
		mv.setViewName("autoIndustry/sales-volume");
		return mv;
	}
//	汽车销量
	@RequestMapping(value = "/first_menu", produces = "application/json;charset=utf-8")
	@ResponseBody
	public String firsMenu() {
		String sendPost ="";
		try {
			sendPost = sendPost(UtilConfig.getURL2().substring(0,UtilConfig.getURL2().length()-1)+"/carsalesranking/carsalesrankingfirst_menu","");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		System.out.println(sendPost);
		return sendPost;
	}
	
	
	@RequestMapping(value = "/second_menu", produces = "application/json;charset=utf-8")
	@ResponseBody
	public String secondMenu(String first_menu) {
		String sendPost ="";
		try {
			sendPost = sendPost(UtilConfig.getURL2().substring(0,UtilConfig.getURL2().length()-1)+"/carsalesranking/carsalesrankingsecond_menu","?&first_menu="+URLEncoder.encode(first_menu, "utf-8"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		System.out.println(sendPost);
		return sendPost;
	}
	
	@RequestMapping(value = "/lesrankinglist", produces = "application/json;charset=utf-8")
	@ResponseBody
	public String lesrankinglist(String first_menu,String second_menu) {
		String sendPost ="";
		try {
			sendPost = sendPost(UtilConfig.getURL2().substring(0,UtilConfig.getURL2().length()-1)+"/carsalesranking/carsalesrankinglist","?&first_menu="+URLEncoder.encode(first_menu, "utf-8")+"&second_menu="+URLEncoder.encode(second_menu, "utf-8"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		System.out.println(sendPost);
		return sendPost;
	}
	
	
	public String esArticle(Map<String, String> map, String api) {
		String size = map.get("size");
		String models_type = map.get("models_type");
		String times = map.get("times");
		String timee = map.get("timee");
		String page = map.get("page");
		String url = es_url + api;
		String params = "size=" + size + "&models_type=" + models_type
				+ "&times=" + times + "&timee=" + timee + "&page=" + page;
//		System.err.println(url + "?" + params);
		String sendPost = "";
		try {
			sendPost = sendPost(url, params);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sendPost;
	}

	public static String sendPost(String url, String params) throws IOException {
		PrintWriter out = null;
		BufferedReader in = null;
		URL realUrl = new URL(url);
	    URLConnection conn = realUrl.openConnection();  
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		out = new PrintWriter(conn.getOutputStream());
		out.print(params);
		out.flush();
		in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
		StringBuilder response = new StringBuilder();
		String line;
		while((line = in.readLine()) != null){
			response.append(line);
		}
		try {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				in.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return response.toString();
	}
}
